// 事件分发器

const _eventNames = ['API:UN_AUTH', 'API:FORBIDDEN', 'API:INVALID', 'ROUTER:CANCEL_PENDING'] as const;

type EventNames = (typeof _eventNames)[number];

class EventEmitter {
  private listeners: Record<EventNames, Set<Function>> = {
    'API:UN_AUTH': new Set(),
    'API:FORBIDDEN': new Set(),
    'API:INVALID': new Set(),
    'ROUTER:CANCEL_PENDING': new Set()
  };

  on(eventName: EventNames, event: Function) {
    // 订阅事件
    this.listeners[eventName]?.add(event);
  }
  emit(eventName: EventNames, ...args: any[]) {
    // 发布事件
    this.listeners[eventName]?.forEach(listener => listener(...args));
  }
  off(eventName: EventNames) {
    // 取消订阅
    this.listeners[eventName]?.clear();
  }
}

export default new EventEmitter();
